var ws = require("nodejs-websocket");
var Base = require('./base');
var colors = require('colors');
const { exec } = require('child_process');

var redis = Base.openRedis('redis读取');
globalConfig = {
    redisSaveLogLimitSum: 110
};
var node_url = process.argv[2];
var server = ws.createServer(function(conn){
	conn.on("text", function (str) {
        try 
        {
           var  obj2 = JSON.parse(str);
            switch(obj2.type)
            {
                case 1:
                    sendTentotal(conn);
                    break;
                case 2:
                     var obj = JSON.parse(str);
                    if (obj.account)
                    {
                        redis.hget("total-gifts",obj.account,function(err,res){
                            if (res)
                            {
                                var data = 
                                {
                                    'type':3,
                                    'mygift':res*1,
                                    'account':obj.account
                                }
                                conn.sendText(JSON.stringify(data));
                            }
                        })
                    }
                    break;
            }
        }
        catch(e)
        {

        }
        
    });
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8888)
Base.initList[0] = function (done) {
    console.log('启动中[0]...');
    console.log('检测EOS区块链连接...');
    Base.checkDockerEOS(node_url, (isCleos, isDocker) => {
        console.log('checkDockerEOS');
        if (isCleos || isDocker) {
            cleosExe = Base.cleosExe;
            done();
            return;
        }
        else {
            done(true, 'can not find cleos');
            return;
        }
    });
}
    
function getBetInfoList() {
    var cmd1 = cleosExe + ' --url ' + node_url + ' get table fastwingifts fastwingifts giftinfo1 -l 200';
    var cmds = []
    cmds.push(cmd1);
    cmd1 = cleosExe + ' --url ' + node_url + ' get table fastwingifts fastwingifts giftinfo2 -l 200';
    cmds.push(cmd1);
    cmd1 = cleosExe + ' --url ' + node_url + ' get table fastwingifts fastwingifts giftinfo3 -l 200';
    cmds.push(cmd1);
    cmd1 = cleosExe + ' --url ' + node_url + ' get table fastwingifts fastwingifts giftinfo4 -l 200';
    cmds.push(cmd1);
    var result = {
        'type':2
    }
    var betinfo = [];
    for (var i=0;i<cmds.length;i++)
    {
        cmd = cmds[i];
        exec(cmd, (err, stdout, stderr) => {
            if (err) { console.log(err); }
            if (stderr) { console.log(stderr); }
            if (stdout) { console.log(stdout); }

            var jsonObj;
            try {
                jsonObj = JSON.parse(stdout);
            } catch (e) {
                try{
                    jsonObj = JSON.parse(stdout + '}],"more": true}');
                }catch (ee)
                {
                    jsonObj = {};
                    //setTimeout(getBetInfoList, 1000);
                    //return;
                }
            }
            var dat = {};
            for (var data in jsonObj.rows) {
                var line = jsonObj.rows[data];

                dat['room' + line.roomid] = line.betinfoList.length

                
                betinfo.push(dat);
                if (betinfo.length == 4)
                {
                    result.betinfo = betinfo;
                    console.log('--------------------'.red+JSON.stringify(result));
                    server.connections.forEach(function(conn) {
                        conn.sendText(JSON.stringify(result));
                    })
                }
            }
        
        });
    }
    setTimeout(getBetInfoList, 2000);
    
}
function notice() {
	redis.spop('notice-all-activebets', (err, res) => {
        if (res)
        {
            try{
                var players = JSON.parse(res);
                var result = {
                    "roomid":players.roomid,
                    "amount":players.amount,
                    "type":1
                }
                var con = [];
                var from;
                var fromindex = 0;
                for (var i =0;i<players.content.length;i++)
                {
                    if (players.amount > players.content[i].payamount)
                    {
                        from = players.content[i].user;
                        fromindex = i;
                        break;
                    }
                }
                for (var i = 0;i<players.content.length;i++)
                {
                    con.push({
                        'from' : from,
                        'to'   : players.content[i].user,
                        'qulity':players.content[i].payamount
                    })
                }
                result.content = con;
                server.connections.forEach(function(conn) {
                    conn.sendText(JSON.stringify(result));
                });
                try{
                    savedata(JSON.stringify(result));
                }catch(ee)
                {
                    console.log(ee)
                }
                
            }catch(e)
            {
                setTimeout(notice, 2000);
                return;
            }
           
		}
    });
	setTimeout(notice, 2000);
}
function pushPerpetualQueue(key,json){
    //判断长度
    redis.scard(key,function(err,len){
        if (len < 10) {
            //添加
            redis.sadd(key,json,function(err,response){
                console.log(err,response);
            });
        }else {
            //删除
            redis.spop(key,function(err,response){
                console.log("删除某一个元素" + response);
            });
        }
    });
}
function savedata(str)
{
    redis.lpush("last-history", str);
    redis.ltrim("last-history",0,100);
}
function sendTentotal(conn)
{
    redis.lrange('last-history', 0, 9, function(err, resp) {
        var data = new Object();
        data.type = 4;
        data.contnet = resp;
        conn.sendText(JSON.stringify(data));    
    });
}


Base.initList[1] = function (done) {
   getBetInfoList();
   notice();
   done();
}
Base.begin();